const log = require('../../util/log')
const config = require('../../util/config')
const chromeMng = require('../chromeMng.20180824')
const {
  Network,
  Page,
  DOM,
  Runtime,
  Emulation
} = chromeMng.client;

async function getJdAdvLink(obj) {
  try {
    obj = obj || {}
    if (!obj.link) {
      return new Promise((resolve, reject) => {
        reject('缺少link')
      })
    }
    obj.times = (obj.times || 0) + 1
    log('getting jd advertising link')
    if (!obj.link.match(/\d+.html/i)) {
      return new Promise((resolve, reject) => {
        reject('link不合法')
      })
    }
    var skuId = obj.link.match(/\d+.html/i)[0]
    skuId = skuId.substring(0, skuId.length - 5)
    return new Promise((resolve, reject) => {
      chromeMng.getJdItems({
        keyword: skuId
      }).then(result => {
        if (result.length == 0) {
          reject('该商品不能返利')
          return
        }
        step2(obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
      }, result => {
        reject(result)
      })
    })
  } catch (err) {
    log(err)
  }
}

async function step2(obj) {
  try {
    obj.times++
    if (obj.times >= config.chromeMaxTimes) {
      return new Promise((resolve, reject) => {
        reject('系统错误')
      })
    }
    log('getting jd advertising link step 2')
    Page.navigate({
      url: 'https://media.jd.com/gotoadv/customPromotion'
    })
    return step2_5(obj)
  } catch (err) {
    log(err)
  }
}

async function step2_5(obj) {
  try {
    obj.times++
    if (obj.times >= config.chromeMaxTimes) {
      return new Promise((resolve, reject) => {
        reject('系统错误')
      })
    }
    log('getting jd advertising link step 2')
    var {result} = await Runtime.evaluate({expression: 'location.href'})
    if (result.value == 'https://media.jd.com/gotoadv/customPromotion') {
      return step3(obj)
    }
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        step2_5(obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
      }, 1000)
    })
  } catch (err) {
    log(err)
  }
}

async function step3(obj) {
  try {
    obj.times++
    if (obj.times >= config.chromeMaxTimes) {
      return new Promise((resolve, reject) => {
        reject('系统错误')
      })
    }
    log('getting jd advertising link step 3')
    var {result} = await Runtime.evaluate({expression: 'location.href'})
    if (result.value != 'https://media.jd.com/gotoadv/customPromotion') {
      return step2(obj)
    }
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#targetCode")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 1) {
      var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#targetCode")[0].value'})
      if (result.value != '') {
        return new Promise(resolve => {
          resolve(result.value)
        })
      }
    }
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#spaceName")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 0) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          step2(obj).then(result => {
            resolve(result)
          }, result => {
            reject(result)
          })
        }, 1000)
      })
    }
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#spaceName")[0].value'})
    if (result.value == '-1') {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          step2(obj).then(result => {
            resolve(result)
          }, result => {
            reject(result)
          })
        }, 1000)
      })
    }

    await Runtime.evaluate({expression: 'document.querySelectorAll("#urlArea")[0].value="' + obj.link + '"'})
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".red-btn")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 0) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          step2(obj).then(result => {
            resolve(result)
          }, result => {
            reject(result)
          })
        }, 1000)
      })
    }
    if (cnt > 1) {
      return new Promise((resolve, reject) => {
        reject('按钮多于1个')
      })
    }
    await Runtime.evaluate({expression: 'document.querySelectorAll(".red-btn")[0].click()'})
    return new Promise(resolve => {
      setTimeout(() => {
        step2(obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
      }, 1000)
    })
  } catch (err) {
    log(err)
  }
}

module.exports = getJdAdvLink
